/**
 * 文件名：AbstractProcess.java
 *
 * 创建人：Elvin Zhao - 279152260@qq.com
 *
 * 创建时间：2019年1月2日 下午3:17:12
 *
 * 版权所有：FNII
 */
package com.z100h.supplychain.core.process;

import java.math.BigDecimal;

import java.util.Date;
import java.util.List;

import org.activiti.editor.language.json.converter.util.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.z100h.supplychain.core.ErpServiceType;
import com.z100h.supplychain.core.EvidenceLockState;
import com.z100h.supplychain.core.EvidenceState;
import com.z100h.supplychain.core.EvidenceType;
import com.z100h.supplychain.core.ProductionState;
import com.z100h.supplychain.core.ResourceLockState;
import com.z100h.supplychain.core.ResourceStockoutLockState;
import com.z100h.supplychain.core.StockoutState;
import com.z100h.supplychain.core.biz.entity.CommonEvidence;
import com.z100h.supplychain.core.biz.entity.Resource;
import com.z100h.supplychain.customer.entity.CustomerStockroom;
import com.z100h.supplychain.customer.service.CustomerStockroomService;
import com.z100h.supplychain.evidence.entity.Stockout;
import com.z100h.supplychain.evidence.entity.StockoutSku;
import com.z100h.supplychain.evidence.entity.WarehouseReceipt;
import com.z100h.supplychain.evidence.service.StockoutErpResourceService;
import com.z100h.supplychain.evidence.service.StockoutService;
import com.z100h.supplychain.evidence.service.StockoutSkuService;
import com.z100h.supplychain.evidence.service.WarehouseReceiptService;
import com.z100h.supplychain.order.service.OrderService;
import com.z100h.supplychain.purchase.entity.PurchaseOrder;
import com.z100h.supplychain.purchase.entity.PurchaseOrderItem;
import com.z100h.supplychain.purchase.entity.PurchaseOrderItemActual;
import com.z100h.supplychain.purchase.service.PurchaseOrderItemActualService;
import com.z100h.supplychain.purchase.service.PurchaseOrderItemService;
import com.z100h.supplychain.purchase.service.PurchaseOrderService;

/**
 * 
 * 出库单抽象类
 *
 * @author Elvin Zhao - 279152260@qq.com
 * @version 1.0 Created on 2019年1月2日 下午7:24:18
 */
public abstract class AbstractStockoutSpecialProcess extends BaseProcess {

	private static final Logger logger = LoggerFactory.getLogger(AbstractStockoutSpecialProcess.class);

	final private String sku0Id = "1515";

	final private String sku1Id = "1516";

	@Autowired
	private PurchaseOrderService purchaseOrderService;

	@Autowired
	private PurchaseOrderItemService purchaseOrderItemService;

	@Autowired
	private WarehouseReceiptService warehouseReceiptService;

	@Autowired
	private PurchaseOrderItemActualService purchaseOrderItemActualService;

	@Autowired
	private OrderService orderService;

	@Autowired
	private CustomerStockroomService customerStockroomService;

	@Autowired
	private StockoutSkuService stockoutSkuService;

	@Autowired
	private StockoutService stockoutService;

	@Autowired
	private StockoutErpResourceService stockoutErpResourceService;

	public static void main(String[] args) {
		BigDecimal purchaseOrderPrice = new BigDecimal("12.3");
		BigDecimal resAmount = new BigDecimal(3);
		BigDecimal[] avgPriceResult = purchaseOrderPrice.divideAndRemainder(resAmount);

		BigDecimal quotientPrice = avgPriceResult[0];
		BigDecimal remainderPrice = avgPriceResult[1];
		System.err.println(quotientPrice);
		System.err.println(remainderPrice);
		if (remainderPrice.equals(new BigDecimal("0"))) {
			System.err.println("+++++++");
		}
	}

	/**
	 * 生成空进空出采购单
	 * 
	 * @author: Elvin Zhao - 279152260@qq.com 
	 * @date: Created on 2019年10月21日 下午5:57:22
	 */
	@Transactional(readOnly = false)
	public void coreProcess(String erpOrderId, BigDecimal purchaseOrderPrice) {

		/**
		 * 1.采购单
		 */
		PurchaseOrder purchaseOrder = new PurchaseOrder();
		purchaseOrder.setState(EvidenceLockState.LOCK.getValue());
		purchaseOrder.setPurchaseDate(new Date());
		purchaseOrder.setRemarks("空进空出采购单！");
		purchaseOrderService.save(purchaseOrder);
		String purchaseOrderId = purchaseOrder.getId();

		/**
		 * 2.入库单
		 */
		CommonEvidence receiptEvidence = new CommonEvidence(EvidenceType.NULLRECEIPT, EvidenceState.FINISH);
		commonEvidenceService.save(receiptEvidence);

		WarehouseReceipt warehouseReceipt = new WarehouseReceipt();
		warehouseReceipt.setEvidenceId(receiptEvidence.getId());
		warehouseReceipt.preInsert();
		warehouseReceiptService.save(warehouseReceipt);

		// 跟新采购单关联的入库单id
		purchaseOrder.setEvidenceId(receiptEvidence.getId());
		purchaseOrderService.save(purchaseOrder);

		/**
		 * 3.出库单
		 */
		CommonEvidence stockOutEvidence = new CommonEvidence(EvidenceType.NULLOUT, EvidenceState.FINISH);
		commonEvidenceService.save(stockOutEvidence);

		Stockout stockout = new Stockout();
		stockout.setEvidenceId(stockOutEvidence.getId());
		stockout.setStockoutState(StockoutState.FINISH.getType());
		CustomerStockroom customerStockroom = customerStockroomService.getCustomerStockroomByOrderId(erpOrderId);
		if (customerStockroom != null) {
			stockout.setCustomerName(customerStockroom.getCustomerName());
			stockout.setCustomerContact(customerStockroom.getContract());
			stockout.setCustomerPhone(customerStockroom.getPhone());
		}
		stockout.preInsert();
		stockoutService.save(stockout);
		/**
		 * 出库单子表
		 * 1.找到仓库对应订单e_rent_order刷生产单ID
		 * 2.将erp的serviceId及serviceType插入sc的sc_e_stockout_order
		 * 3.将erp需要出库资源Id插入sc的sc_e_stockout_erp_resource
		 * 
		 */

		// 1.刷ERP表关联
		orderService.updateOrderStockoutId(stockOutEvidence.getId(), erpOrderId);
		// 2.插入子表
		stockoutService.insertStockoutOrder(ErpServiceType.ORDERIN.getType(), erpOrderId, stockOutEvidence.getId());
		// 3.插入资源
		stockoutErpResourceService.insertOrderErpResource(stockOutEvidence.getId(),
				stockOutEvidence.getCreateBy().getId(), erpOrderId);

		stockoutErpResourceService.updateResQcState(stockOutEvidence.getId(), ProductionState.OUTFINISH.getType());

		savePurchaseOrderItems(purchaseOrderId, receiptEvidence.getId(), stockOutEvidence.getId(), erpOrderId,
				purchaseOrderPrice);

		// 4 插入resource_log
		resourceLogService.resourceLogging(stockOutEvidence.getId(), ResourceLockState.UNLOCK);
		resourceLogService.updateLogEid(stockOutEvidence.getId(), receiptEvidence.getId());
		resourceLogService.resourceLogging(stockOutEvidence.getId(), ResourceLockState.UNLOCK);
	}

	/**
	 * 生成空进空出
	 * 采购单
	 * 入库单
	 * 资源
	 * erpsku
	 * 
	 * @param purchaseOrderId
	 * @param erpOrderId
	 * @param purchaseOrderPrice
	 * @author: Elvin Zhao - 279152260@qq.com 
	 * @date: Created on 2019年10月21日 下午6:23:41
	 */
	@Transactional(readOnly = false)
	private void savePurchaseOrderItems(String purchaseOrderId, String receiptId, String stockOutId, String erpOrderId,
			BigDecimal purchaseOrderPrice) {

		/**
		 * 获取贴码RESID
		 */
		List<String> erpResIdList = stockoutErpResourceService.getOrderErpResId(erpOrderId);

		if (CollectionUtils.isNotEmpty(erpResIdList)) {

			Integer erpResAmount = erpResIdList.size();

			BigDecimal resAmount = new BigDecimal(erpResIdList.size());

			/**
			 * 
			 * 采购价格/数量
			 * 判断是否整除，
			 * 整除的话只有一个sku0的价格=商 
			 * 不能整除取一个sku1的价格=商+余数 
			 * 数量需要控制 如果不能整除 sku0=数量-1 sku1= 1
			 * 
			 */
			BigDecimal[] avgPriceResult = purchaseOrderPrice.divideAndRemainder(resAmount);
			BigDecimal quotientPrice = avgPriceResult[0];
			BigDecimal remainderPrice = avgPriceResult[1];

			if (!remainderPrice.equals(new BigDecimal("0"))) {
				/**
				 * purchaseOrderItem
				 */
				PurchaseOrderItem purchaseOrderItemSku1 = new PurchaseOrderItem();
				purchaseOrderItemSku1.setSkuId(sku1Id);
				purchaseOrderItemSku1.setNum(1);
				purchaseOrderItemSku1.setPrice(quotientPrice.add(remainderPrice));
				purchaseOrderItemSku1.setPurchaseOrderId(purchaseOrderId);
				purchaseOrderItemSku1.setCreateDate(new Date());
				purchaseOrderItemService.save(purchaseOrderItemSku1);
				/**
				 * purchaseOrderItemActual
				 */
				PurchaseOrderItemActual purchaseOrderItemActualSku1 = new PurchaseOrderItemActual();
				purchaseOrderItemActualSku1.setSkuId(sku1Id);
				purchaseOrderItemActualSku1.setNum(1);
				purchaseOrderItemActualSku1.setPrice(quotientPrice.add(remainderPrice));
				purchaseOrderItemActualSku1.setWarehouseReceiptId(receiptId);
				purchaseOrderItemActualService.save(purchaseOrderItemActualSku1);

				Resource resource = new Resource();
				resource.setErpResId(erpResIdList.get(erpResIdList.size() - 1));
				resource.setSkuId(sku1Id);
				resource.setEvidenceId(stockOutId);
				resource.setEvidenceLock(EvidenceLockState.UNLOCK.getValue());// 默认解锁
				resource.setStockoutLock(ResourceStockoutLockState.LOCK.getValue());// 默认解锁
				resourceService.addResource(resource);// 先插入

				StockoutSku sku1 = new StockoutSku();
				sku1.setEvidenceId(stockOutId);
				sku1.setAmount(1);
				sku1.setSkuId(Integer.valueOf(sku1Id));
				sku1.setSkuPrice(quotientPrice.add(remainderPrice));
				sku1.setAmountOut(1);
				stockoutSkuService.save(sku1);

				erpResAmount -= 1;
			}
			/**
			 * purchaseOrderItem
			 */
			PurchaseOrderItem purchaseOrderItemSku0 = new PurchaseOrderItem();
			purchaseOrderItemSku0.setSkuId(sku0Id);
			purchaseOrderItemSku0.setNum(erpResAmount);
			purchaseOrderItemSku0.setPrice(quotientPrice);
			purchaseOrderItemSku0.setPurchaseOrderId(purchaseOrderId);
			purchaseOrderItemSku0.setCreateDate(new Date());
			purchaseOrderItemService.save(purchaseOrderItemSku0);
			/**
			 * purchaseOrderItemActual
			 */
			PurchaseOrderItemActual purchaseOrderItemActualSku0 = new PurchaseOrderItemActual();
			purchaseOrderItemActualSku0.setSkuId(sku0Id);
			purchaseOrderItemActualSku0.setNum(erpResAmount);
			purchaseOrderItemActualSku0.setPrice(quotientPrice);
			purchaseOrderItemActualSku0.setWarehouseReceiptId(receiptId);
			purchaseOrderItemActualService.save(purchaseOrderItemActualSku0);

			for (int j = 0; j < erpResAmount; j++) {
				Resource resource = new Resource();
				resource.setErpResId(erpResIdList.get(j));
				resource.setSkuId(sku0Id);
				resource.setEvidenceId(stockOutId);
				resource.setEvidenceLock(EvidenceLockState.UNLOCK.getValue());// 默认解锁
				resource.setStockoutLock(ResourceStockoutLockState.LOCK.getValue());// 默认解锁
				resourceService.addResource(resource);// 先插入
			}

			StockoutSku sku0 = new StockoutSku();
			sku0.setEvidenceId(stockOutId);
			sku0.setAmount(erpResAmount);
			sku0.setSkuId(Integer.valueOf(sku0Id));
			sku0.setSkuPrice(quotientPrice);
			sku0.setAmountOut(erpResAmount);
			stockoutSkuService.save(sku0);

		}
	}
}
